package com.aba.bms.lend;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

class LibraryManager<records> {
    private final List<BorrowRecord> records = new ArrayList();
    private long recordIdCounter = 1;
 
    public void borrowBook(long userId, long bookId) {
        BorrowRecord record = new BorrowRecord();
        record.id = recordIdCounter++;
        record.userId = userId;
        record.bookId = bookId;
        record.borrowDate = LocalDate.now();
        record.dueDate = LocalDate.now().plusDays(14);
        record.status = "BORROWED";
        
        records.add(record);
        System.out.println("借阅成功，记录ID: " + record.id);
        checkOverdue(); // 每次操作后检查逾期
    }
 
    public void returnBook(long recordId) {
        BorrowRecord record = findRecord(recordId);
        if (record == null) {
            System.out.println("记录不存在");
            return;
        }
 
        record.returnDate = LocalDate.now();
        record.status = "RETURNED";
        
        // 计算逾期费用
        if (record.returnDate.isAfter(record.dueDate)) {
            long days = record.dueDate.until(record.returnDate).getDays();
            record.overdueFee = BigDecimal.valueOf(days * 0.5);
        }
        System.out.println("归还成功，逾期费用: " + record.overdueFee);
    }
 
    public void showRecords(long userId) {
        System.out.println("\n=== 借阅记录 ===");
        records.stream()
            .filter(r -> userId == 0 || r.userId == userId)
            .forEach(r -> {
                System.out.printf("ID:%-4d 用户:%-4d 书籍:%-4d 状态:%-8s 应还:%s 实还:%s 费用:%s\n",
                    r.id, r.userId, r.bookId, r.status, 
                    r.dueDate, 
                    r.returnDate != null ? r.returnDate : "未归还",
                    r.overdueFee);
            });
    }
 
    private void checkOverdue() {
        LocalDate today = LocalDate.now();
        records.stream()
            .filter(r -> r.status.equals("BORROWED"))
            .filter(r -> today.isAfter(r.dueDate))
            .forEach(r -> {
                r.status = "OVERDUE";
                System.out.println("检测到逾期记录: " + r.id);
            });
    }
 
    private BorrowRecord findRecord(long id) {
        return records.stream()
            .filter(r -> r.id == id)
            .findFirst()
            .orElse(null);
    }
}
